/**
 * Created by horace on 16-8-2.
 */
//Make sure jQuery has been loaded before network_policy.js
if (typeof jQuery === "undefined") {
  throw new Error("This JS requires jQuery");
}

var table;
var $addRoomModal = $("#addRoomModal");
var roomId;
var roomName;
var address;
var contacts;
var contacts_tel;
var ajaxType;
var ajaxUrl;

toastr.options = {
  "closeButton": true,
  "debug": false,
  "newestOnTop": false,
  "progressBar": false,
  "positionClass": "toast-top-center",
  "preventDuplicates": false,
  "onclick": null,
  "showDuration": "300",
  "hideDuration": "1000",
  "timeOut": "2000",
  "extendedTimeOut": "1000",
  "showEasing": "swing",
  "hideEasing": "linear",
  "showMethod": "fadeIn",
  "hideMethod": "fadeOut"
};

$(document).ready(function () {
    table = $('.responsive-data-table').DataTable({
        "PaginationType": "bootstrap",
        "processing": true,
        "ajax": list_url,
        "responsive": true,
        "language": {
            "url": "/static/js/i18n/Chinese.json"
            },
        "dom": '<"tbl-top clearfix"lfr>,t,<"tbl-footer clearfix"<"tbl-info pull-left"i><"tbl-pagin pull-right"p>>',
        "columns": [
                {"data": 'id'},
                {"data": "name"},
                {"data": 'address'},
                {"data": 'contacts'},
                {"data": 'contacts_tel'},
                {
                  "data": null,
                  "orderable": false,
                }
        ],
        "columnDefs": [
            {'targets': [ 0 ], 'visible': false, 'searchable': false},
            {'targets': [ 5 ] ,"width": "10%",
                render: function (data, type, row, meta) {
                    var html = '<button class="btn btn-primary btn-xs" onclick=row_edit('+row.id+')><i class="fa fa-pencil"></i></button>'
                             + '<button class="btn btn-danger btn-xs" onclick=row_del('+row.id+')><i class="fa fa-trash-o "></i></button>';
                    return html;
                }
            }
        ],
        "order": [[0, 'asc']],
    });

    $("#btn-addRoom").on('click', function () {
        $('#my-modal-title').text('新增机房');
        $('#roomId').parent().parent().hide();
        $('#roomName').val('');
        $('#address').val('');
        $('#contacts').val('');
        $('#contacts_tel').val('');
        $addRoomModal.modal('show');

    });

    $('#btn-saveRoom').on('click',function () {
        roomId = $('#roomId').val();
        roomName = $('#roomName').val();
        address = $('#address').val();
        contacts = $('#contacts').val();
        contacts_tel = $('#contacts_tel').val();

        if (!(roomName && address && contacts && contacts_tel)){
            toastr["error"]("请确保都已经填充数据！", "错误");
            return false;
        }

        if(roomId){ajaxType = 'put'; ajaxUrl=post_url+'/'+roomId}else{ajaxType='post'; ajaxUrl=post_url}

        var json_data=$.toJSON({
            'id': roomId,
            'name':roomName,
            'address': address,
            'contacts': contacts,
            'contacts_tel': contacts_tel
        });


        $.ajax({
            type: ajaxType,
            url: ajaxUrl,
            data: json_data,
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            success: function (data) {
                table.ajax.reload();
                $addRoomModal.modal("hide");
                toastr["success"]("操作成功！", "成功")
            },
            error: function (xhr, status, data) {
                toastr["error"](eval(xhr.responseJSON)['detail'], "错误")
            }
        })

    });
});


// =================== refresh panel ===============

    $('.box-refresh').on('click', function(br) {
        br.preventDefault();
        $("<div class='refresh-block'><span class='refresh-loader'><i class='fa fa-spinner fa-spin'></i></span></div>").appendTo($(this).parents('.tools').parents('.panel-heading').parents('.panel'));
        table.ajax.reload();
        setTimeout(function() {
            $('.refresh-block').remove();
        }, 1000);

    });

// ======================== function ==================
function row_edit(id){
    $('#my-modal-title').text('修改机房');
    $.ajax({
        type: 'get',
        url: get_url+'/'+id,
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        success: function (data) {
            $('#roomId').val(data.data.id);
            $('#roomName').val(data.data.name);
            $('#address').val(data.data.address);
            $('#contacts').val(data.data.contacts);
            $('#contacts_tel').val(data.data.contacts_tel);
            $addRoomModal.modal('show');
        },
        error: function () {
            toastr["error"]("获取数据异常！", "错误")
        }

    });
}

function row_del(id) {
        $.confirm({
            title: '确认',
            content: '确定要删除该条数据么？',
            confirm: function(){
                $.ajax({
                    type: 'delete',
                    url: get_url+'/'+id,
                    dataType: "json",
                    contentType: "application/json; charset=utf-8",
                    success: function (data) {
                        toastr["success"]("删除成功！", "成功");
                        table.ajax.reload();
                    },
                    error: function () {
                        toastr["error"]("删除数据异常！", "错误")
                    }
                })
            },
            confirmButton: '删除',
            confirmButtonClass: 'btn-danger',
            cancelButton: '取消',
            cancelButtonClass: 'btn-primary',
            keyboardEnabled: true,
        });
}